package ltd.dujiabao.dualwrite.controller;

import ltd.dujiabao.dualwrite.domain.Person;
import ltd.dujiabao.dualwrite.dao.PersonRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;

/**
 * @author Bowie Du
 * @date 2025/11/1 00:24
 */
@RestController
public class PersonController {

    @Autowired
    private PersonRepository personRepository;

    @GetMapping("/person/{id}")
    public Person getPerson(@PathVariable("id") Long id) {
        return personRepository.findById(id).orElse(null);
    }

    @PostMapping("/person")
    public Person addPerson(@RequestBody Person person) {
        personRepository.save(person);
        return person;
    }

    @PostMapping("/persons")
    public List<Person> addPersons(@RequestBody List<Person> persons) {
        personRepository.saveAll(persons);
        return persons;
    }

    @PutMapping("/person")
    @Transactional(rollbackFor = Exception.class)
    public void updatePerson(@RequestBody Person person) {
        Optional<Person> optional = personRepository.findById(person.getId());
        if (optional.isEmpty()) {
            return;
        }
        personRepository.save(person);
    }

    @DeleteMapping("/person/{id}")
    public void deletePerson(@PathVariable(name = "id") Long id) {
        personRepository.deleteById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/testRollback")
    public Person testRollback(@RequestBody Person person) {
        personRepository.save(person);
        if (person.getId() % 2 == 0) {
            throw new RuntimeException("测试回滚");
        }
        return person;
    }
}
